package scfg.utils;

import java.io.*;
import java.util.*;

import scfg.output.Display;
import scfg.output.RNAFormattedFile;

public class MfeAquire {
	
	public static String getGTfoldDBStructure(String filename) {
		return getGTfoldDBStructure(filename, null, null);
	}
	
	public static String getGTfoldDBStructure(String filename, String constraintsName, String outputName) {
		if (filename != null && constraintsName != null && outputName != null)
			return getGTfoldDBStructure(new File(filename), new File(constraintsName), new File(outputName));
		if (filename != null && constraintsName != null)
			return getGTfoldDBStructure(new File(filename), new File(constraintsName), null);
		if (filename != null && outputName != null)
			return getGTfoldDBStructure(new File(filename), null, new File(outputName));
		if (filename != null)
			return getGTfoldDBStructure(new File(filename), null, null);
		return null;
	}
	
	public static String getGTfoldDBStructure(File sequenceFile, File constraintsFile, File outputFile) {
		if (sequenceFile == null || !sequenceFile.exists()) {
			// TODO:
			return null;
		}
		try {
			StringBuilder exe = new StringBuilder("gtfold");
			if (constraintsFile != null && constraintsFile.exists())
				exe.append(" -c ").append(constraintsFile.getAbsolutePath());
			if (outputFile != null)
				exe.append(" -o ").append(outputFile.getAbsolutePath());
			exe.append(" ").append(sequenceFile.getAbsolutePath());
			Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", exe.toString()});
			p.waitFor();
			Scanner scan = new Scanner(p.getInputStream());
	        StringBuilder sb = new StringBuilder();
	        int lineNum = 0;
	        String str = null;
	        while (scan.hasNextLine()) {
	        	String line = scan.nextLine().trim();
	        	if (line.matches("[.()]+"))
	        		str = line;
	            sb.append(lineNum++).append("\t").append(line).append("\n");
	        }
	        return str;
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String filename = "/home/david/Documents/RNA/ct_files/sequences/5S/d.5.e.E.woodruffi.seq";
		String constraintsName = "/home/david/Documents/RNA/ct_files/con/5S/d.5.e.E.woodruffi.cnstr";
		getGTfoldDBStructure(filename, constraintsName, null);
	}

}
